package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-05-12
 */
@RestController
@RequestMapping("/eduorder/order")
//@CrossOrigin //用nginx需要加
public class OrderController {
    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "生成订单")
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId,HttpServletRequest request){
        //根据token字符串获取用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        String orderId = orderService.createOrder(courseId,userId);
        return  R.ok().data("orderId",orderId);
    }

    @ApiOperation(value = "根据订单id查询订单信息")
    @GetMapping("/getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        QueryWrapper<Order> wrapper=new QueryWrapper();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return  R.ok().data("item",order);
    }
    @ApiOperation(value = "查询订单表中订单的状态 判断课程是否购买")
    @GetMapping("/isBought/{courseId}")
    public R isBought(@PathVariable String courseId,HttpServletRequest request){
        //根据token字符串获取用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        QueryWrapper<Order> wrapper=new QueryWrapper();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",userId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if(count>0)
            return  R.ok().data("isBought",true);
        else
            return  R.ok().data("isBought",false);
    }
}

